<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出入库记录</title>
    <link rel="stylesheet" href="/static/static/inventoryStyle.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        @media (max-width: 900px) {
            .container { padding: 6px !important; }
            table { font-size: 13px; }
        }
    </style>
</head>
<body>
<div class="container">
    <h2>出入库记录</h2>
    <!--    <button onclick="exportInventoryRecords()">导出记录</button>-->
    <button onclick="addInventory()">添加</button>
    <!-- 用于显示物资的出库记录的表格 -->
    <div id="inventory-list">
        <!-- 出入库记录列表 -->
    </div>
    <!-- 分页按钮 -->
    <div id="pagination"></div>
    <!-- 返回按钮 -->
    <button onclick="goBack()">返回</button>
    <div id="productId">
        <!-- 物资添加弹出框 -->
        <div id="inventoryModal" style="display:none;">
            <form id="inventoryForm">
                <label for="userName">管理员：</label>
                <input type="text" id="userName" name="userName">
                <br>
                <label for="quantity">数量：</label>
                <input type="number" id="quantity" name="quantity">
                <br>
                <label for="type">类型：</label>
                <select id="type" name="type">
                    <option value="in">入库</option>
                    <option value="out">出库</option>
                </select>
                <br>
                <label for="created_at">时间：</label>
                <input type="datetime-local" id="created_at" name="created_at">
                <br>
                <label for="remark">出入库原因：</label>
                <input type="text" id="remark" name="remark">
                <br>
                <button type="submit">添加物资</button>
                <button type="button" onclick="closeAddProductModal()">取消</button>
            </form>
        </div>
    </div>

    <script src="/static/static/script.js"></script>

    <script>

        const urlParams = new URLSearchParams(window.location.search);

        // 获取 'name' 参数的值
        const name = urlParams.get('name');

        // 输出 'name' 的值
        console.log('name',name);
        let titleElement = document.querySelector('title');
        titleElement.textContent = name + " - 出入库记录";
        let h2Element = document.querySelector('h2');
        h2Element.textContent = name + " - 出入库记录";
        // 在页面加载时获取物资ID并显示出库记录
        document.addEventListener('DOMContentLoaded', function() {
            const productId = {{.ProductId}};  // 这是由后端模板渲染的变量
            window.currentProductId = productId;
            fetchInventoryRecords(productId);
            // 检查是否存在超过一周未处理的记录并提示
            checkOverdueAndAlert();
        });


        // 获取并显示出库记录
        async function fetchInventoryRecords(productId) {
            const id = document.getElementById('productId');
            id.setAttribute('productId',productId);
            const response = await fetch(`/api/inventory?product_id=${productId}&page=${invenCurrentPage}&page_size=${invenPerPage}`);
            const data = await response.json();
            const records = data.records;
            const totalCount = data.total_count;
            const totalPages = data.total_pages;
            const inventoryList = document.getElementById('inventory-list');
            inventoryList.innerHTML = ''; // 清空当前内容

            if (records.length === 0) {
                inventoryList.textContent = '暂无出库记录';
                return;
            }

            // 按日期分组记录
            const groupedRecords = {};
            records.forEach(record => {
                const id = document.getElementById('productId');
                id.setAttribute('productId',record.product_id);
                
                const date = new Date(record.gmt_create);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const dateKey = `${month}月${day}日`;
                
                if (!groupedRecords[dateKey]) {
                    groupedRecords[dateKey] = [];
                }
                groupedRecords[dateKey].push(record);
            });

            // 创建按日期分组的列表
            const container = document.createElement('div');
            container.style.cssText = 'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.6; background: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);';

            // 按日期排序（最新的在前）
            const sortedDates = Object.keys(groupedRecords).sort((a, b) => {
                const dateA = new Date(groupedRecords[a][0].gmt_create);
                const dateB = new Date(groupedRecords[b][0].gmt_create);
                return dateB - dateA;
            });

            sortedDates.forEach(dateKey => {
                // 创建日期标题
                const dateHeader = document.createElement('div');
                dateHeader.style.cssText = 'font-size: 18px; font-weight: bold; margin: 25px 0 15px 0; color: #2c3e50; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; padding: 8px 0; border-bottom: 3px solid #007bff; position: relative;';
                
                // 添加日期图标和样式
                dateHeader.innerHTML = `
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <span style="font-size: 20px;">📅</span>
                        <span>${dateKey}</span>
                        <div style="flex: 1; height: 2px; background: linear-gradient(90deg, #007bff, transparent); margin-left: 10px;"></div>
                    </div>
                `;
                container.appendChild(dateHeader);

                // 创建该日期的记录列表
                const recordsList = document.createElement('ol');
                recordsList.style.cssText = 'margin: 0 0 25px 0; padding: 0; list-style: none; counter-reset: item;';

                groupedRecords[dateKey].forEach((record, index) => {
                    const listItem = document.createElement('li');
                    listItem.style.cssText = 'margin: 12px 0; padding: 16px; background: #f8f9fa; border-left: 4px solid #007bff; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.1); position: relative; counter-increment: item;';
                    
                    const time = new Date(record.gmt_create);
                    const hours = String(time.getHours()).padStart(2, '0');
                    const minutes = String(time.getMinutes()).padStart(2, '0');
                    const seconds = String(time.getSeconds()).padStart(2, '0');
                    const timeStr = `${hours}:${minutes}:${seconds}`;
                    
                    const typeText = record.type === 'in' ? '入库' : '出库';
                    const typeColor = record.type === 'in' ? '#28a745' : '#dc3545';
                    const typeBgColor = record.type === 'in' ? '#d4edda' : '#f8d7da';
                    
                    listItem.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px;">
                            <div style="flex: 1; min-width: 300px; position: relative; padding-left: 40px;">
                                <div style="position: absolute; left: 0; top: 0; width: 28px; height: 28px; background: linear-gradient(135deg, #007bff, #0056b3); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 14px; box-shadow: 0 2px 4px rgba(0,123,255,0.3);">
                                    ${index + 1}
                                </div>
                                <div style="display: flex; align-items: center; margin-bottom: 10px; flex-wrap: wrap; gap: 10px;">
                                    <span style="font-weight: bold; color: ${typeColor}; background: ${typeBgColor}; padding: 6px 12px; border-radius: 6px; font-size: 14px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">[${typeText}]</span>
                                    <span style="color: #495057; font-weight: 600; font-size: 15px;">数量: <span style="color: #007bff; font-weight: bold; font-size: 16px;">${record.quantity}</span></span>
                                </div>
                                <div style="display: flex; align-items: center; margin-bottom: 8px; flex-wrap: wrap; gap: 16px;">
                                    <span style="color: #6c757d; font-size: 14px; display: flex; align-items: center; gap: 4px;">👤 <span style="color: #495057; font-weight: 500;">${record.user_name}</span></span>
                                    <span style="color: #6c757d; font-size: 14px; display: flex; align-items: center; gap: 4px;">🕒 <span style="color: #495057; font-weight: 500;">${timeStr}</span></span>
                                </div>
                                <div style="margin-top: 8px;">
                                    <span style="color: #6c757d; font-size: 14px; display: flex; align-items: center; gap: 4px;">📝 <span style="color: #495057; font-weight: 500;">${record.remark || '无备注'}</span></span>
                                </div>
                            </div>
                            <div style="display: flex; align-items: center; gap: 8px; margin-top: 8px;">
                                <button onclick="deleteInventory(${record.id})" style="padding: 8px 16px; background: linear-gradient(135deg, #dc3545, #c82333); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; transition: all 0.2s; box-shadow: 0 2px 4px rgba(220,53,69,0.3);" onmouseover="this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 8px rgba(220,53,69,0.4)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(220,53,69,0.3)'">🗑️ 删除</button>
                            </div>
                        </div>
                    `;
                    recordsList.appendChild(listItem);
                });

                container.appendChild(recordsList);
            });

            inventoryList.appendChild(container);
            createPagination(totalPages);
        }

        // 检查是否有超过一周的记录并弹窗提示
        async function checkOverdueAndAlert() {
            try {
                const resp = await fetch('/api/email/overdue');
                const data = await resp.json();
                if (data && data.overdue) {
                    alert('提示：存在超过一周未处理的出/入库记录，请及时处理。');
                }
            } catch (e) {
                console.error('检查超期记录失败', e);
            }
        }
        let invenCurrentPage = 1;
        const invenPerPage = 10;
        // 创建分页按钮
        function createPagination(totalPages) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';  // 清空现有分页按钮

            // 设置分页容器样式
            pagination.style.margin = '20px 0';
            pagination.style.display = 'flex';
            pagination.style.justifyContent = 'center';
            pagination.style.gap = '5px';
            pagination.style.flexWrap = 'wrap';

            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.textContent = '上一页';
            prevButton.style.padding = '5px 10px';
            prevButton.style.border = '1px solid #ddd';
            prevButton.style.borderRadius = '3px';
            prevButton.style.cursor = 'pointer';
            prevButton.style.backgroundColor = '#fff';
            prevButton.style.color = '#000';

            if (invenCurrentPage === 1) {
                prevButton.disabled = true;
                prevButton.style.opacity = '0.5';
            } else {
                prevButton.onclick = () => changePage(invenCurrentPage - 1, totalPages);
            }
            pagination.appendChild(prevButton);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.style.padding = '5px 10px';
                pageButton.style.border = '1px solid #ddd';
                pageButton.style.borderRadius = '3px';
                pageButton.style.cursor = 'pointer';
                pageButton.style.color = '#000';

                if (i === invenCurrentPage) {
                    // 当前页样式
                    pageButton.style.backgroundColor = 'red';
                    pageButton.style.color = 'white';
                    pageButton.style.border = '1px solid darkred';
                    pageButton.style.fontWeight = 'bold';
                } else {
                    // 其他页样式
                    pageButton.style.backgroundColor = '#fff';
                    pageButton.onclick = () => changePage(i, totalPages);
                }
                pagination.appendChild(pageButton);
            }

            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.textContent = '下一页';
            nextButton.style.padding = '5px 10px';
            nextButton.style.border = '1px solid #ddd';
            nextButton.style.borderRadius = '3px';
            nextButton.style.cursor = 'pointer';
            nextButton.style.backgroundColor = '#fff';
            nextButton.style.color = '#000';

            if (invenCurrentPage === totalPages) {
                nextButton.disabled = true;
                nextButton.style.opacity = '0.5';
            } else {
                nextButton.onclick = () => changePage(invenCurrentPage + 1, totalPages);
            }
            pagination.appendChild(nextButton);
        }

        // 切换页码
        function changePage(page,totalPages) {
            if (page < 1 || page > totalPages) return;  // 防止页码越界
            invenCurrentPage = page;
            const productId = window.currentProductId;
            fetchInventoryRecords(productId);
        }


        // 打开模态框
        function addInventory(recordId) {
            document.getElementById('inventoryModal').style.display = 'block';
        }

        // 关闭模态框
        function closeAddProductModal() {
            document.getElementById('inventoryModal').style.display = 'none';
        }

        // 导出出库记录
        function exportInventoryRecords() {
            window.location.href = `/api/inventory/export?product_id=${window.currentProductId}`;
        }

        // 返回上一页
        function goBack() {
            window.history.back()
            // window.location.replace(document.referrer);
            // window.location.go(1)
            // window.location.href="/"
            // window.location.reload();
        }
        //添加接口
        document.getElementById('inventoryForm').addEventListener('submit', function(event) {
            event.preventDefault();  // 阻止表单默认提交行为

            // 获取表单数据
            const userName = document.getElementById('userName').value;
            const quantity = document.getElementById('quantity').value;
            const type = document.getElementById('type').value;
            const created_at = document.getElementById('created_at').value;
            const remark = document.getElementById('remark').value;
            const productId = document.getElementById('productId');
            const id = parseInt(productId.getAttribute('productId'));
            // 这里你可以自定义自己的逻辑，如验证数据或发送到后端
            // console.log('id:', id);
            // console.log('Type:', type);
            // console.log('Time:', created_at);
            // console.log('Remark:', remark);

            // 调用自定义的方法，例如发送数据到后端
            sendDataToBackend(id,quantity, type, remark,created_at,userName);
        });

        // 自定义方法：将数据发送到后端
        async function sendDataToBackend(id,quantity, type, remark,created_at,userName) {
            id = id || '';
            quantity = parseInt(quantity)
            quantity = quantity || '';
            type = type || '';
            created_at = created_at || '';
            remark = remark || '';
            userName = userName || '';
            console.log('userNmae',userName)
            await fetch(`/api/inventory/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    product_id:id,
                    quantity: quantity,
                    type: type,
                    created_at: created_at,
                    remark: remark,
                    user_name:userName
                })
            }).then(res=>{
                res.json().then(r=>{
                    if (r.error) {
                        alert('添加物资失败:'+r.error);
                    } else {
                        console.log('添加物资成功');
                    }
                })
            });


            const productId = document.getElementById('productId');
            const pid = parseInt(productId.getAttribute('productId'));
            fetchInventoryRecords(pid)
            closeAddProductModal();
        }

        // 关闭模态框的函数
        function closeAddProductModal() {
            document.getElementById('inventoryModal').style.display = 'none';
        }

        // 密码验证相关变量
        let passwordVerified = false;
        let passwordVerifiedTime = null;
        const PASSWORD_EXPIRE_TIME = 10 * 60 * 1000; // 10分钟（毫秒）

        // 检查密码是否在有效期内
        function isPasswordValid() {
            if (!passwordVerified || !passwordVerifiedTime) {
                return false;
            }
            const now = new Date().getTime();
            return (now - passwordVerifiedTime) < PASSWORD_EXPIRE_TIME;
        }

        // 显示密码输入对话框
        function showPasswordDialog() {
            return new Promise((resolve) => {
                // 创建模态框
                const modal = document.createElement('div');
                modal.style.cssText = `
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 1000;
                `;

                // 创建对话框内容
                const dialog = document.createElement('div');
                dialog.style.cssText = `
                    background: white;
                    padding: 30px;
                    border-radius: 8px;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                    min-width: 300px;
                    text-align: center;
                `;

                dialog.innerHTML = `
                    <h3 style="margin: 0 0 20px 0; color: #333;">删除确认</h3>
                    <p style="margin: 0 0 15px 0; color: #666;">请输入删除密码以确认操作：</p>
                    <input type="password" id="deletePassword" placeholder="请输入密码" 
                           style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 20px; font-size: 14px;">
                    <div style="display: flex; gap: 10px; justify-content: center;">
                        <button id="confirmDelete" style="padding: 8px 20px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">确认删除</button>
                        <button id="cancelDelete" style="padding: 8px 20px; background: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">取消</button>
                    </div>
                `;

                modal.appendChild(dialog);
                document.body.appendChild(modal);

                // 获取元素
                const passwordInput = document.getElementById('deletePassword');
                const confirmBtn = document.getElementById('confirmDelete');
                const cancelBtn = document.getElementById('cancelDelete');

                // 自动聚焦到密码输入框
                passwordInput.focus();

                // 确认删除
                confirmBtn.onclick = async () => {
                    const password = passwordInput.value.trim();
                    if (!password) {
                        alert('请输入密码');
                        return;
                    }
                    
                    try {
                        const isValid = await verifyPassword(password);
                        if (isValid) {
                            passwordVerified = true;
                            passwordVerifiedTime = new Date().getTime();
                            document.body.removeChild(modal);
                            resolve(true);
                        } else {
                            alert('密码错误，请重新输入！');
                            passwordInput.value = '';
                            passwordInput.focus();
                        }
                    } catch (error) {
                        alert('密码验证失败: ' + error.message);
                        passwordInput.value = '';
                        passwordInput.focus();
                    }
                };

                // 取消删除
                cancelBtn.onclick = () => {
                    document.body.removeChild(modal);
                    resolve(false);
                };

                // 按回车键确认
                passwordInput.onkeypress = (e) => {
                    if (e.key === 'Enter') {
                        confirmBtn.click();
                    }
                };

                // 点击模态框背景关闭
                modal.onclick = (e) => {
                    if (e.target === modal) {
                        document.body.removeChild(modal);
                        resolve(false);
                    }
                };
            });
        }

        // 验证密码（调用后端API）
        async function verifyPassword(password) {
            try {
                const response = await fetch('/api/password/verify', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        password: password
                    })
                });
                
                const data = await response.json();
                return data.valid;
            } catch (error) {
                console.error('密码验证失败:', error);
                return false;
            }
        }

        // 删除库存记录
        async function deleteInventory(inventoryId) {
            // 检查密码是否有效
            if (!isPasswordValid()) {
                const passwordConfirmed = await showPasswordDialog();
                if (!passwordConfirmed) {
                    return; // 用户取消或密码错误
                }
            }

            // 确认删除
            if (confirm('确定要删除这条记录吗？')) {
                try {
                    const response = await fetch(`/api/inventory/${inventoryId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        alert('删除成功');
                        // 重新加载记录列表
                        const productId = window.currentProductId;
                        fetchInventoryRecords(productId);
                    } else {
                        const error = await response.json();
                        alert('删除失败: ' + (error.error || '未知错误'));
                    }
                } catch (error) {
                    alert('删除失败: ' + error.message);
                }
            }
        }

    </script>

</body>
</html>
